---
import table from "@/assets/formula/crafting_table.png";
import SingleItem from "./components/SingleItem.astro";
import type { CraftingShapedFormula } from "@/types/formula";
import useIcon from "@/hooks/useIcon";
import type { FormulaItem } from "@/types/formula";
import { Image } from "astro:assets";
import { AstroError } from "astro/errors";

export interface Props {
  formula: CraftingShapedFormula;
  alt?: string;
}

const {
  formula: { result, pattern, key },
  alt = "合成配方",
} = Astro.props;

const resultIcon = useIcon((result as FormulaItem).item);

if (!resultIcon) throw new AstroError(`找不到以下物品图标: ${result}`);

const res: Array<ReturnType<typeof useIcon> | null> = [];

pattern
  .join("")
  .split("")
  .forEach((v) => {
    if (key[v]) {
      res.push(useIcon(key[v].item)!);
    } else {
      res.push(null);
    }
  });
---

<div class="relative mb-1 w-80 h-40 origin-top-left md:scale-100 scale-90">
  <Image src={table} alt={alt} class="!bg-transparent" />
  <div class="absolute w-[108px] top-[32px] left-[44px] flex flex-wrap">
    {
      res.map((v) => (
        <div class="m-[2px] w-8 h-8">
          {v ? (
            <SingleItem src={v.smallIcon} title={v.name} id={v.registerName} />
          ) : undefined}
        </div>
      ))
    }
  </div>
  <div class="absolute left-[226px] top-[62px] p-2">
    <SingleItem
      src={resultIcon.smallIcon}
      title={resultIcon.name}
      count={result.count}
    />
  </div>
</div>
